import java.io.*;
import java.net.*;

import java.util.*;

class EchoHandler implements Runnable{
    Socket socket = null;
    OutputStream os = null;
    InputStream is = null;  
    public EchoHandler(Socket socket){
        this.socket = socket;
    }

    public void run(){
        try{
            is = socket.getInputStream();
            os = socket.getOutputStream();

            while (true){
                byte[] b = new byte[1024];
                int n = is.read(b);
                System.out.println("Client Send:\t" + new String(b, 0, n));
                os.write(b, 0, n);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
                is.close();
                socket.close();
            } catch (Exception e) {}
        }
    }

}

public class EchoServerMultiThread {
    ServerSocket serverSocket = null; 
    int port = 10001;
    public void run() throws Exception{
        serverSocket = new ServerSocket(port);
        while (true){
            Socket socket = serverSocket.accept();
            EchoHandler run = new EchoHandler(socket);
            Thread t = new Thread(run);
            t.start();
        }
    }
    public void start() {
        try {
            run();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                serverSocket.close();
            } catch (Exception e) {}
        }
    }

    public static void main(String argv[]){
        EchoServerMultiThread server = new EchoServerMultiThread();
        server.start();
    }
}
